<template>
  <div>
    <el-dialog
      :title="this.houseFormData.id ? '编辑房产' : '新增房产'"
      :visible="isShowDialog"
      @close="btnCancel"
    >
      <el-form
        label-width="90px"
        ref="houseForm"
        :model="houseFormData"
        :rules="rules"
      >
        <el-form-item label="经纪:" prop="agent">
          <el-select
            v-model="houseFormData.agent"
            @blur="blurAgent"
            placeholder="请选择经纪人"
          >
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分类:" prop="category">
          <el-select
            v-model="houseFormData.category"
            @blur="blurCategory"
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in categoryList"
              :label="item.title"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标题:" prop="title">
          <el-input
            v-model="houseFormData.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>

        <el-form-item label="标签:">
          <el-tag
            :key="tag"
            v-for="tag in labelList"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>

          <el-input
            class="input-new-tag"
            v-model="inputValue"
            v-if="inputVisible"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>

          <el-button
            class="button-new-tag"
            v-else
            size="small"
            @click="showInput"
            >+ 新标签</el-button
          >
        </el-form-item>

        <el-form-item label="地址:">
          <VDistpicker
            :province="addressList.province"
            :city="addressList.city"
            :area="addressList.area"
            @selected="siteSelect"
          ></VDistpicker>
        </el-form-item>

        <el-form-item label="价格:" prop="price">
          <el-input
            v-model="houseFormData.price"
            placeholder="请输入整数的价格"
          ></el-input>
        </el-form-item>

        <el-form-item label="描述:" prop="desc">
          <el-input
            v-model="houseFormData.desc"
            type="textarea"
            :rows="5"
            placeholder="描述一下您的房产吧"
          ></el-input>
        </el-form-item>

        <el-form-item label="内容">
          <VueEditor :config="config" ref="vueEditor"></VueEditor>
        </el-form-item>

        <el-form-item label="介绍图片:" prop="image">
          <UploadImage ref="houseImage" :limit="3"></UploadImage>
        </el-form-item>

        <el-form-item label="封面" prop="image">
          <UploadImage ref="CoverImage" :limit="1"></UploadImage>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-row type="flex" justify="center">
          <el-button @click="btnCancel" class="btnCancel">取消</el-button>
          <el-button type="primary" @click="btnOk" class="btnOk"
            >确定</el-button
          >
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import VDistpicker from "v-distpicker";
import { addHouse, getHouseById, updateHouse } from "@/api/house";
export default {
  props: {
    isShowDialog: {
      type: Boolean,
      default: false,
    },
  },

  components: {
    VueEditor,
    VDistpicker,
  },

  data() {
    const priceValidator = (rule, val, callback) => {
      if (/^(1|[1-9][0-9]*)$/.test(val)) {
        callback();
      } else {
        callback(new Error("价格格式有误"));
      }
    };
    return {
      inputVisible: false,
      inputValue: "",
      labelList: ["风景优美"],
      cityList: "",
      categoryList: [],
      agentList: [],

      addressList: {
        province: "",
        city: "",
        area: "",
      },

      houseFormData: {
        title: "",
        desc: "",
        image: "",
        agent: "",
        content: "",
        address: "",
        price: "",
        photos: [],
        tags: "",
        category: "",
      },

      config: {
        // 上传图片的配置
        uploadImage: {
          url: "http://localhost:8000/upload",
          name: "file",
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert("http://localhost:8000" + res.data.url);
          },
        },
      },

      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        desc: [{ required: true, message: "描述不能为空", trigger: "blur" }],
        agent: [{ required: true, message: "经纪人不能为空", trigger: "blur" }],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" },
          {
            validator: priceValidator,
            trigger: "blur",
          },
        ],
        category: [
          { required: true, message: "分类不能为空", trigger: "blur" },
        ],
        image: [{ required: true, message: "图片不能为空", trigger: "change" }],
      },
    };
  },

  async created() {
    await this.$store.dispatch("category/getCategoryList");
    await this.$store.dispatch("agent/getAgent");

    this.categoryList = this.$store.state.category.categoryList;

    this.agentList = this.$store.getters.agentList;
  },

  methods: {
    resetCommon() {
      this.$emit("update:isShowDialog", false);
      this.$emit("updateHouseList");
      this.$refs.houseForm.resetFields();
      this.labelList = ["风景优美"];
      this.$refs.vueEditor.editor.root.innerHTML = "";
      this.$refs.houseImage.fileList = [];
      this.$refs.CoverImage.fileList = [];
      this.houseFormData = {
        title: "",
        desc: "",
        image: "",
        agent: "",
        content: "",
        address: "",
        price: "",
        photos: [],
        tags: "",
        category: "",
      };

      this.addressList = {
        province: "省",
        city: "市",
        area: "区",
      };
    },

    btnCancel() {
      this.resetCommon();
    },

    handleClose(tag) {
      this.labelList.splice(this.labelList.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.labelList.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    async btnOk() {
      try {
        if (this.$refs.vueEditor.editor.root.innerText.length <= 1) {
          this.$message.error("内容还没有输入");
          return;
        }
        const coverImage = this.$refs.CoverImage.fileList;
        this.houseFormData.image = coverImage[0] ? coverImage[0].url : "";

        this.$refs.houseForm.validateField("image");

        await this.$refs.houseForm.validate();

        this.houseFormData.content = this.$refs.vueEditor.editor.root.innerHTML;

        this.houseFormData.tags = this.labelList;

        const houseImageArr = [];
        this.$refs.houseImage.fileList.forEach((item) => {
          houseImageArr.push(item.url);
        });
        this.houseFormData.photos = houseImageArr;

        if (this.houseFormData.id) {
          await updateHouse(this.houseFormData);
        } else {
          await addHouse(this.houseFormData);
        }

        this.$message.success(
          this.houseFormData.id ? "编辑房产成功" : "新增房产成功"
        );

        this.resetCommon();
      } catch (error) {
        console.log(error);
      }
    },

    siteSelect(data) {
      this.houseFormData.address =
        data.province.value + "," + data.city.value + "," + data.area.value;
    },

    blurAgent() {
      setTimeout(() => {
        this.$refs.houseForm.validateField("agent");
      }, 100);
    },

    blurCategory() {
      setTimeout(() => {
        this.$refs.houseForm.validateField("category");
      }, 100);
    },

    async getHouseById(id) {
      const houseInfo = await getHouseById(id);
      this.houseFormData = houseInfo;
      this.labelList = houseInfo.tags;

      this.$nextTick(() => {
        this.$refs.CoverImage.fileList = [
          { url: houseInfo.image ? houseInfo.image : "" },
        ];

        houseInfo.photos.forEach((item) => {
          this.$refs.houseImage.fileList.push({ url: item });
        });

        this.$refs.vueEditor.editor.root.innerHTML = houseInfo.content;
      });

      const addressInfo = houseInfo.address.split(",");
      this.addressList = {
        province: addressInfo[0],
        city: addressInfo[1],
        area: addressInfo[2],
      };

      this.$emit("update:isShowDialog", true);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-dialog__header {
  background-color: #6cf;
  .el-dialog__title {
    color: #fff;
  }
}

/deep/.el-dialog__body {
  .el-input--suffix .el-input__inner {
    width: 250px;
  }
  .el-input__inner {
    width: 100%;
  }
  .input-new-tag {
    .el-input__inner {
      width: 60px;
    }
  }
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.btnCancel {
  margin-right: 50px;
}
.btnOk {
  margin-left: 50px;
}
</style>